<!--
 * @Description: 语言选择组件
 * @Version: 2.0
 * @Autor: lhl
 * @Date: 2021-08-21 19:18:50
 * @LastEditors: lhl
 * @LastEditTime: 2021-08-22 10:57:08
-->
<template>
  <van-popup v-model="showPicker" v-bind="popupConfig">
    <van-picker
      show-toolbar
      item-height="1rem"
      swipe-duration="300"
      :title="$t('appHeader.pickerTitle')"
      :columns="langs"
      :default-index="defaultIndex"
      @confirm="onConfirm"
      @cancel="onClose"
    />
  </van-popup>
</template>

<script>
import { Locale } from "vant";
import { setLanguage } from "Utils/cookies";
import { mapGetters, mapMutations } from "vuex";

export default {
  name: "LangSelect",
  props: {
    popupConfig: {
      type: Object,
      default: () => ({
        overlay: true,
        position: "bottom",
        duration: 0.3,
        closeOnPopstate: true,
        transitionAppear: true,
        safeAreaInsetBottom: true,
      }),
    },
  },
  data() {
    return {
      langs: [
        {
          text: "中文（简体）",
          value: "zh-CN",
        },
        {
          text: "中文（繁体）",
          value: "zh-TW",
        },
        {
          text: "English",
          value: "en-US",
        },
        {
          text: "日本語",
          value: "ja-JP",
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["langPicker"]),
    showPicker: {
      get() {
        return this.langPicker;
      },
      set(val) {
        this.toggleLangPicker(val);
      },
    },
    defaultIndex() {
      return (
        this.langs.findIndex((item) => item.value === this.$i18n.locale) || 0
      );
    },
  },
  methods: {
    ...mapMutations(["toggleLangPicker"]),
    onConfirm({ value }) {
      // Vant basic
      Locale.use(value, this.$i18n.messages[value]);
      // Business component
      this.$i18n.locale = value;
      // Cookie
      setLanguage(value);
      this.toggleLangPicker(false);
    },
    onClose() {
      this.toggleLangPicker(false);
    },
  },
};
</script>
